package com.frank.libandroid;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import com.frank.libandroid.butterknife.ButterKnife;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseFragment<V extends ViewDataBinding> extends Fragment {
    protected V mBinding;
    protected String TAG = this.getClass().getSimpleName();
    protected BaseActivity mActivity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (BaseActivity) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Class<V> generic = (Class<V>) ReflectUtil.getGeneric(this, 0);
        try {
            Method method = generic.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            mBinding = (V) method.invoke(null, inflater, container, false);
            return mBinding.getRoot();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
    }

    protected void start(Class<? extends Activity> clazz) {
        Intent starter = new Intent(getContext(), clazz);
        startActivity(starter);
    }

    protected void start(Class<? extends Activity> clazz, Object param) {
        Intent starter = new Intent(getContext(), clazz);
        DataStore.put(clazz.getName(), param);
        startActivity(starter);
    }

    protected void initData() {
    }

    protected void initView() {
        ButterKnife.bind(this, getView());
    }
}
